package com.mypan.uitls;


import lombok.SneakyThrows;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.math.BigDecimal;

@Component
public class PictureCompress {
    public static final String compressDir = FileUtil.basePath + "\\compressDir";

    // 图片压缩测试方法
    public static void pictureCompressTest() {
        String src = "D:\\Desktop\\0.jpg";
        String dest = "D:\\Desktop\\1.jpg";
        pictureCompress(src, dest, 1024 * 100L, 0.5);
    }

    /**
     * 图片压缩处理方法
     *
     * @param srcPath  图片源文件路径
     * @param destPath 输出文件路径
     * @param fileSize 限制在多大时停止压缩
     * @param accuracy 压缩图片的精细度
     */
    @SneakyThrows
    public static Boolean pictureCompress(String srcPath, String destPath, long fileSize, double accuracy) {
        final File srcFile = new File(srcPath);
        long length = srcFile.length();   /* 如果图片本身不够大的话就不需要做任何处理 */
        if (length < fileSize) {
            return false;
        }
        BufferedImage bim = ImageIO.read(srcFile);

        int imgWidth = bim.getWidth();
        int imgHeight = bim.getHeight();

        int desWidth = new BigDecimal(imgWidth).multiply(new BigDecimal(accuracy)).intValue();
        int desHeight = new BigDecimal(imgHeight).multiply(new BigDecimal(accuracy)).intValue();

        Thumbnails.of(srcPath).size(desWidth, desHeight).outputQuality(accuracy).toFile(destPath); /* 压缩之后，使用输出后的文件递归，重复写入处理，直到大小满意 */
        pictureCompress(destPath, destPath, fileSize, accuracy);
        return true;
    }

    public static void main(String[] args) {
        pictureCompressTest();
    }
}
